<template>
	<view class="match-evaluation-container">
		<!-- 页面头部 -->
		<view class="page-header">
			<text class="page-title">比赛评价</text>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-section" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 比赛信息 -->
		<view class="match-info-section" v-else-if="matchData">
			<view class="info-card">
				<view class="card-title">比赛信息</view>
				<view class="info-list">
					<view class="info-item">
						<text class="info-label">比赛名称：</text>
						<text class="info-value">{{matchData.match_title}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">比赛时间：</text>
						<text class="info-value">{{formatDateTime(matchData.match_date)}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">比赛地点：</text>
						<text class="info-value">{{matchData.match_venue}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">对阵双方：</text>
						<text class="info-value">{{matchData.home_team}} VS {{matchData.away_team}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">比赛级别：</text>
						<text class="info-value">{{matchData.match_level}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 裁判员评价表单 -->
		<view class="evaluation-section" v-if="matchData && refereeRecords.length > 0">
			<view class="section-title">裁判员评价 ({{refereeRecords.length}}人)</view>
			
			<view class="referee-evaluation-card" v-for="(record, index) in refereeRecords" :key="record._id">
				<view class="referee-header">
					<view class="referee-info">
						<text class="referee-name">{{record.referee_name}}</text>
						<text class="referee-position" :class="{
						'position-main': record.position === '主裁判',
						'position-assistant': record.position === '助理裁判' || record.position === '边裁判',
						'position-fourth': record.position === '第四官员',
						'position-supervisor': record.position === '裁判监督'
					}">{{record.position}}</text>
					</view>
					<view class="evaluation-status" v-if="evaluations[record._id] && evaluations[record._id].completed">
						<text class="status-completed">已评价</text>
					</view>
				</view>
				
				<!-- 裁判监督不需要评价 -->
				<view class="supervisor-notice" v-if="record.position === '裁判监督'">
					<text class="notice-text">裁判监督无需评价，系统自动确认</text>
				</view>
				
				<!-- 其他裁判员的评价表单 -->
				<view class="evaluation-form" v-else>
					<!-- 出勤状态 -->
					<view class="form-group">
						<view class="form-label">出勤状态</view>
						<view class="radio-group">
							<view class="radio-item" v-for="status in attendanceOptions" :key="status.value"
								@click="updateEvaluation(record._id, 'attendance_status', status.value)">
								<view class="radio-icon" :class="{'checked': getEvaluationValue(record._id, 'attendance_status') === status.value}"></view>
								<text class="radio-label">{{status.label}}</text>
							</view>
						</view>
					</view>
					
					<!-- 执裁评分 -->
					<view class="form-group">
						<view class="form-label">执裁评分 (可选)</view>
						<view class="radio-group">
							<view class="radio-item" v-for="rating in ratingOptions" :key="rating.value"
								@click="updateEvaluation(record._id, 'execution_rating', rating.value)">
								<view class="radio-icon" :class="{'checked': getEvaluationValue(record._id, 'execution_rating') === rating.value}"></view>
								<text class="radio-label">{{rating.label}}</text>
							</view>
						</view>
						
						<!-- 自定义评分输入 -->
						<view class="custom-rating-section">
							<view class="custom-rating-label">或输入自定义分数 (0-100分，可选)：</view>
							<input class="custom-rating-input" type="number" placeholder="不填写则不评分"
								:value="getCustomRating(record._id)"
								@input="updateCustomRating(record._id, $event)"
								min="0" max="100">
						</view>
					</view>
					
					<!-- 执裁费用 -->
					<view class="form-group">
						<view class="form-label">执裁费用 (元)</view>
						<input class="form-input" type="number" placeholder="请输入执裁费用"
							:value="getEvaluationValue(record._id, 'referee_fee')"
							@input="updateEvaluationInput(record._id, 'referee_fee', $event)">
					</view>
					
					<!-- 表现评价 -->
					<view class="form-group">
						<view class="form-label">表现评价</view>
						<textarea class="form-textarea" placeholder="请输入对裁判员表现的详细评价"
							:value="getEvaluationValue(record._id, 'performance_evaluation')"
							@input="updateEvaluationInput(record._id, 'performance_evaluation', $event)">
						</textarea>
					</view>
					

				</view>
			</view>
		</view>
		
		<!-- 底部操作按钮 -->
		<view class="bottom-actions" v-if="matchData">
			<button class="save-draft-btn" @click="saveDraft">保存草稿</button>
			<button class="submit-btn" @click="submitEvaluation" :disabled="!canSubmit">提交确认</button>
		</view>
		
		<!-- 错误状态 -->
		<view class="error-section" v-else-if="!loading">
			<text class="error-text">比赛数据加载失败</text>
			<button class="retry-btn" @click="loadMatchData">重新加载</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			loading: true,
			matchKey: '',
			matchData: null,
			refereeRecords: [],
			evaluations: {}, // 存储每个裁判员的评价数据
			
			// 选项数据
			attendanceOptions: [
				{ label: '正常出勤', value: '正常出勤' },
				{ label: '迟到', value: '迟到' },
				{ label: '早退', value: '早退' },
				{ label: '缺勤', value: '缺勤' }
			],
			ratingOptions: [
				{ label: '优秀 (90-100分)', value: 95 },
				{ label: '良好 (80-89分)', value: 85 },
				{ label: '一般 (70-79分)', value: 75 },
				{ label: '较差 (60-69分)', value: 65 },
				{ label: '不合格 (60分以下)', value: 50 }
			]
		}
	},
	
	computed: {
		// 是否可以提交
		canSubmit() {
			// 检查所有非监督员的裁判员是否都已评价
			const nonSupervisorRecords = this.refereeRecords.filter(r => r.position !== '裁判监督')
			
			return nonSupervisorRecords.every(record => {
				const evaluation = this.evaluations[record._id]
				if (!evaluation || !evaluation.attendance_status) {
					return false
				}
				
				// 评分为可选项，但如果填写了需要验证范围
				const rating = evaluation.execution_rating
				if (rating !== '' && rating !== null && rating !== undefined) {
					const numRating = parseFloat(rating)
					if (isNaN(numRating) || numRating < 0 || numRating > 100) {
						return false
					}
				}
				
				return true
			})
		}
	},
	
	onLoad(options) {
		if (options.matchKey) {
			this.matchKey = options.matchKey
			this.loadMatchData()
		} else {
			this.loading = false
			uni.showToast({
				title: '比赛信息缺失',
				icon: 'none'
			})
		}
	},
	
	methods: {
		// 加载比赛数据
		async loadMatchData() {
			this.loading = true
			try {
				// 从本地存储获取比赛数据
				const storedData = uni.getStorageSync('currentMatchEvaluation')
				if (storedData) {
					this.matchData = JSON.parse(storedData)
					this.refereeRecords = this.matchData.records || []
					this.initializeEvaluations()
				} else {
					throw new Error('比赛数据不存在')
				}
			} catch (error) {
				console.error('加载比赛数据失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		// 初始化评价数据
		initializeEvaluations() {
			const evaluations = {}
			this.refereeRecords.forEach(record => {
				evaluations[record._id] = {
					attendance_status: record.attendance_status || '正常出勤',
					execution_rating: record.execution_rating || (record.position === '裁判监督' ? 95 : ''),
					referee_fee: record.referee_fee || '',
					performance_evaluation: record.performance_evaluation || '',
					completed: false
				}
			})
			this.evaluations = evaluations
		},
		
		// 更新评价数据
		updateEvaluation(recordId, field, value) {
			if (!this.evaluations[recordId]) {
				this.evaluations[recordId] = {}
			}
			this.evaluations[recordId][field] = value
			this.$forceUpdate()
		},
		
		// 更新输入框评价数据
		updateEvaluationInput(recordId, field, event) {
			const value = event.detail.value
			this.updateEvaluation(recordId, field, value)
		},
		
		// 获取评价值
		getEvaluationValue(recordId, field) {
			return this.evaluations[recordId] ? this.evaluations[recordId][field] : ''
		},
		
		// 获取自定义评分
		getCustomRating(recordId) {
			const rating = this.getEvaluationValue(recordId, 'execution_rating')
			// 如果是数字且不在预设选项中，则显示为自定义分数
			if (typeof rating === 'number' && !this.ratingOptions.some(opt => opt.value === rating)) {
				return rating
			}
			return ''
		},
		
		// 更新自定义评分
		updateCustomRating(recordId, event) {
			const value = parseFloat(event.detail.value)
			if (isNaN(value) || value < 0 || value > 100) {
				uni.showToast({
					title: '评分范围：0-100分',
					icon: 'none'
				})
				return
			}
			this.updateEvaluation(recordId, 'execution_rating', value)
		},
		

		
		// 保存草稿
		async saveDraft() {
			uni.showToast({
				title: '草稿已保存',
				icon: 'success'
			})
		},
		
		// 提交评价
		async submitEvaluation() {
			if (!this.canSubmit) {
				uni.showToast({
					title: '请完成所有必填项',
					icon: 'none'
				})
				return
			}
			
			uni.showModal({
				title: '确认提交',
				content: '确认提交比赛评价？提交后将无法修改。',
				success: async (res) => {
					if (res.confirm) {
						await this.doSubmitEvaluation()
					}
				}
			})
		},
		
		// 执行提交评价
		async doSubmitEvaluation() {
			try {
				uni.showLoading({
					title: '提交中...'
				})
				
				// 准备提交数据
				const evaluationData = {
					match_id: this.matchData.match_id,
					match_date: this.matchData.match_date,
					evaluations: []
				}
				
				this.refereeRecords.forEach(record => {
					const evaluation = this.evaluations[record._id]
					if (record.position === '裁判监督') {
						// 裁判监督自动确认为正常出勤，无需评价
						evaluationData.evaluations.push({
							record_id: record._id,
							attendance_status: '正常出勤',
							execution_rating: 95, // 默认优秀评分
							performance_evaluation: '监督员正常履职',
							referee_fee: 0
						})
					} else {
						// 其他裁判员使用评价数据
						const evaluationItem = {
							record_id: record._id,
							attendance_status: evaluation.attendance_status,
							performance_evaluation: evaluation.performance_evaluation,
							referee_fee: parseFloat(evaluation.referee_fee) || 0
						}
						
						// 评分为可选项，只有填写了才添加
						if (evaluation.execution_rating !== '' && evaluation.execution_rating !== null && evaluation.execution_rating !== undefined) {
							evaluationItem.execution_rating = evaluation.execution_rating
						}
						
						evaluationData.evaluations.push(evaluationItem)
					}
				})
				
				console.log('提交评价数据:', evaluationData)
				
				// 验证数据完整性
				if (!evaluationData.evaluations || evaluationData.evaluations.length === 0) {
					uni.hideLoading()
					uni.showToast({
						title: '没有需要确认的记录',
						icon: 'none'
					})
					return
				}
				
				// 调用云函数提交评价
				const refereeRecordService = uniCloud.importObject('referee-record-service')
				const result = await refereeRecordService.confirmMatchRecords(evaluationData)
				
				uni.hideLoading()
				
				console.log('提交结果:', result)
				
				if (result.code === 0) {
					const successCount = result.data?.success || 0
					const totalCount = result.data?.total || 0
					
					uni.showToast({
						title: `提交成功 (${successCount}/${totalCount})`,
						icon: 'success'
					})
					
					// 清除本地存储的比赛数据
					uni.removeStorageSync('currentMatchEvaluation')
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: result.message || '提交失败',
						icon: 'none'
					})
				}
				
			} catch (error) {
				uni.hideLoading()
				console.error('提交评价失败:', error)
				uni.showToast({
					title: '提交失败',
					icon: 'none'
				})
			}
		},
		
		// 格式化日期时间
		formatDateTime(dateStr) {
			if (!dateStr) return ''
			const date = new Date(dateStr)
			return date.getFullYear() + '-' + 
				   String(date.getMonth() + 1).padStart(2, '0') + '-' + 
				   String(date.getDate()).padStart(2, '0') + ' ' +
				   String(date.getHours()).padStart(2, '0') + ':' + 
				   String(date.getMinutes()).padStart(2, '0')
		}
	}
}
</script>

<style lang="scss" scoped>
.match-evaluation-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx; // 为底部按钮留出空间
}

.page-header {
	background-color: #fff;
	padding: 30rpx 20rpx;
	text-align: center;
	border-bottom: 2rpx solid #f0f0f0;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.loading-section {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 40rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

.match-info-section {
	padding: 20rpx;
}

.info-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-bottom: 15rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.info-list {
	// 样式继承自之前的info相关样式
}

.info-item {
	display: flex;
	margin-bottom: 12rpx;
}

.info-label {
	font-size: 26rpx;
	color: #666;
	width: 140rpx;
	flex-shrink: 0;
}

.info-value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.evaluation-section {
	padding: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.referee-evaluation-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.referee-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 25rpx;
	padding-bottom: 15rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.referee-info {
	display: flex;
	align-items: center;
}

.referee-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-right: 15rpx;
}

.referee-position {
	font-size: 22rpx;
	padding: 4rpx 8rpx;
	border-radius: 10rpx;
	color: #fff;
}

.position-main {
	background-color: #ff6b6b;
}

.position-assistant {
	background-color: #4ecdc4;
}

.position-fourth {
	background-color: #45b7d1;
}

.position-supervisor {
	background-color: #96ceb4;
}

.position-default {
	background-color: #999;
}

.evaluation-status {
	// 评价状态样式
}

.status-completed {
	font-size: 24rpx;
	color: #28a745;
	background-color: #d4edda;
	padding: 4rpx 8rpx;
	border-radius: 10rpx;
}

.supervisor-notice {
	text-align: center;
	padding: 30rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
}

.notice-text {
	font-size: 26rpx;
	color: #6c757d;
}

.evaluation-form {
	// 评价表单样式
}

.form-group {
	margin-bottom: 30rpx;
}

.form-label {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 15rpx;
}

.radio-group {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.radio-item {
	display: flex;
	align-items: center;
	padding: 10rpx 15rpx;
	border: 2rpx solid #e9ecef;
	border-radius: 20rpx;
	background-color: #fff;
}

.radio-icon {
	width: 30rpx;
	height: 30rpx;
	border: 2rpx solid #ccc;
	border-radius: 50%;
	margin-right: 10rpx;
	position: relative;
}

.radio-icon.checked {
	border-color: #007aff;
	background-color: #007aff;
}

.radio-icon.checked::after {
	content: '';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 12rpx;
	height: 12rpx;
	background-color: #fff;
	border-radius: 50%;
}

.radio-label {
	font-size: 26rpx;
	color: #333;
}

.form-input {
	width: 100%;
	padding: 20rpx;
	border: 2rpx solid #e9ecef;
	border-radius: 12rpx;
	font-size: 26rpx;
	background-color: #fff;
}

.form-textarea {
	width: 100%;
	min-height: 120rpx;
	padding: 20rpx;
	border: 2rpx solid #e9ecef;
	border-radius: 12rpx;
	font-size: 26rpx;
	background-color: #fff;
	resize: vertical;
}

.custom-rating-section {
	margin-top: 20rpx;
	padding: 20rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
}

.custom-rating-label {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.custom-rating-input {
	width: 100%;
	padding: 15rpx;
	border: 2rpx solid #e9ecef;
	border-radius: 8rpx;
	font-size: 26rpx;
	background-color: #fff;
	text-align: center;
}

.bottom-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx;
	border-top: 2rpx solid #f0f0f0;
	display: flex;
	gap: 20rpx;
}

.save-draft-btn, .submit-btn {
	flex: 1;
	height: 80rpx;
	border: none;
	border-radius: 40rpx;
	font-size: 30rpx;
	font-weight: bold;
}

.save-draft-btn {
	background-color: #6c757d;
	color: #fff;
}

.submit-btn {
	background-color: #28a745;
	color: #fff;
}

.submit-btn:disabled {
	background-color: #ccc;
	color: #999;
}

.error-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
}

.error-text {
	font-size: 28rpx;
	color: #dc3545;
	margin-bottom: 30rpx;
}

.retry-btn {
	padding: 15rpx 30rpx;
	background-color: #007aff;
	color: #fff;
	border: none;
	border-radius: 20rpx;
	font-size: 26rpx;
}
</style> 